package com.dingding.service.user.core.taxi.dao.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.dao.impl.BaseDaoImpl;
import com.dingding.common.core.base.daox.IBaseDaoX;
import com.dingding.common.core.base.daox.ICriteriaBaseDao;
import com.dingding.common.core.base.daox.ISQLBaseDao;
import com.dingding.common.core.beans.special.Specialuserlogin;
import com.dingding.common.core.beans.special.Specialuserposition;
import com.dingding.common.core.beans.special.Specialuservehicleinfo;
import com.dingding.common.core.exception.bussiness.BizExpEnum;
import com.dingding.common.core.exception.bussiness.BussinessException;
import com.dingding.common.core.exception.server.ServerException;
import com.dingding.common.core.exception.server.ServerExpEnum;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.common.core.util.oss.upload.ImageUpload;
import com.dingding.facade.user.dto.taxi.ReqTaxiUserAuthDTO;
import com.dingding.facade.user.dto.taxi.RespTaxiUserAuthDTO;
import com.dingding.facade.user.dto.taxi.enu.CarAuthStatus;
import com.dingding.service.user.core.taxi.dao.ITaxiUserDao;

/**
 * 
 * @ClassName: TaxiUserDaoImpl
 * @Description: 出租车认证相关业务
 * @author haoxiaojun
 * @date 2016年11月22日 上午11:50:37
 */
@SuppressWarnings("all")
@Transactional(propagation = Propagation.REQUIRED)
@Component("taxiUserDao")
public class TaxiUserDaoImpl extends BaseDaoImpl<Specialuserposition> implements ITaxiUserDao {

	@Resource(name = "baseDaoX")
	private IBaseDaoX baseDaoX;

	@Resource(name = "SQLBaseDao")
	private ISQLBaseDao isqlBaseDao;

	@Resource(name = "criteriaBaseDao")
	private ICriteriaBaseDao criteriaBaseDao;

	Logger log = Logger.getLogger(this.getClass());

	/**
	 * @Title: TaxiUserController.java
	 * @Package com.dingding.special.controller
	 * @Description: 通过Id查找出租车用户的司机
	 * @author haoxiaojun
	 * @date 2016年11月21日 下午5:41:03
	 * @version V2.5.6
	 */
	@Transactional(readOnly = true)
	public Specialuservehicleinfo getTaxiUserVehicleInfo(String userId) {

		try {
			Specialuserlogin login = this.baseDaoX.getById(userId, Specialuserlogin.class);
			if (login == null) {
				log.error("没有id为" + userId + "的用户！DriverUserDaoImpl：getSpecialUserVehicleInfo()");
				return null;
			}
		} catch (Exception e) {
			log.error("查询用户信息出错！DriverUserDaoImpl：getSpecialUserVehicleInfo()", e);
			throw new ServerException(ServerExpEnum.SERVER_DATABASE_EXCEPTION);
		}

		Specialuservehicleinfo specialuservehicleinfo = null;
		List<Specialuservehicleinfo> vlist = null;
		try {
			vlist = (List<Specialuservehicleinfo>) super.listSqlFreeObject(
					"select * from specialuservehicleinfo where userId = ?", Specialuservehicleinfo.class, userId);
		} catch (Exception e) {
			log.error("查询用户的车辆信息出错！DriverUserDaoImpl：getSpecialUserVehicleInfo()", e);
			throw new ServerException(ServerExpEnum.SERVER_DATABASE_EXCEPTION);
		}

		if (vlist == null || vlist.size() == 0) {
			specialuservehicleinfo = new Specialuservehicleinfo();
			specialuservehicleinfo.setUserId(userId);
			try {
				baseDaoX.save(specialuservehicleinfo);
			} catch (Exception e) {
				log.error("查询用户的车辆信息出错！DriverUserDaoImpl：getSpecialUserVehicleInfo()", e);
				throw new ServerException(ServerExpEnum.SERVER_DATABASE_EXCEPTION);
			}
			return specialuservehicleinfo;
		} else {
			return vlist.get(0);
		}
	}

	/**
	 * @Title: TaxiUserController.java
	 * @Package com.dingding.special.controller
	 * @Description: 出租车主认证
	 * @author haoxiaojun
	 * @date 2016年11月21日 下午1:40:45
	 * @version V2.5.6
	 */
	public Specialuservehicleinfo saveTaxiUserVehicleInfo(ReqTaxiUserAuthDTO reqTaxiUserAuth) {
		// 判断车牌是否被认证过
		boolean isReg = this.isLisenceIsReg(reqTaxiUserAuth.getLisencePlate(), reqTaxiUserAuth.getUserId());

		if (isReg == false) {
			// 获取该用户的车主认证信息
			Specialuservehicleinfo specialuservehicleinfo = this.getTaxiUserVehicleInfo(reqTaxiUserAuth.getUserId());
			
			// 1：审核中  2：审核通过   3：审核未通过
			Integer status = specialuservehicleinfo.getSuvStatus(); 
																	 
			if (status == null || (status != 1 && status != 2) || (status == 0)) {
				
				BeanUtils.copyProperties(reqTaxiUserAuth, specialuservehicleinfo);
				
				// 1：审核中 2：审核通过 3：审核未通过
				specialuservehicleinfo.setSuvStatus(1);
				
				// 	1：缺省值(游客) 2：专车车主 3:出租车车主
				specialuservehicleinfo.setAuthType(reqTaxiUserAuth.getUserRole());
				
				specialuservehicleinfo.setSubmitTime(new Date());

				//上传图片工具类实例化
				ImageUpload imageUpload = new ImageUpload();
				// 上传图片
				String jszImageName = imageUpload.upLoadPicture(reqTaxiUserAuth.getJszImage());
				String xszImageName = imageUpload.upLoadPicture(reqTaxiUserAuth.getXszImage());
				String vehiImageName = imageUpload.upLoadPicture(reqTaxiUserAuth.getVehicleImage());
				
				if (ToolUtil.isNotBlank(jszImageName) && ToolUtil.isNotBlank(xszImageName)
						&& ToolUtil.isNotBlank(vehiImageName)) {
					specialuservehicleinfo.setXszImage(xszImageName);
					specialuservehicleinfo.setVehicleImage(vehiImageName);
					this.baseDaoX.update(specialuservehicleinfo);
					return specialuservehicleinfo;
				} else {
					log.error("上传车辆图片的时候出错！DriverUserDaoImpl : saveSpecialUserVehicleInfo()");
					throw new ServerException(ServerExpEnum.UPLOAD_IMAGE_ERROR);
				}
			} else {
				log.error("用户的审核状态为审核中或审核通过，不能认证！DriverUserDaoImpl : saveSpecialUserVehicleInfo()");
				throw new BussinessException(BizExpEnum.USER_VEHI_CAR_STATUS_ERROR);
			}
		} else {
			log.error("该车辆已经已被其他用户使用！DriverUserDaoImpl : saveSpecialUserVehicleInfo()");
			throw new BussinessException(BizExpEnum.VEHI_IS_BE_REGED);
		}
	}

	/**
	 * @Title: TaxiUserController.java
	 * @Package com.dingding.special.controller
	 * @Description: 判断车主是否认证过
	 * @author haoxiaojun
	 * @date 2016年11月21日 下午4:45:03
	 * @version V2.5.6
	 */
	@Transactional(readOnly = true)
	public boolean isLisenceIsReg(String lisencePlate, String userId) {
		List<Specialuservehicleinfo> vlist = null;

		try {
			vlist = (List<Specialuservehicleinfo>) super.listSqlFreeObject(
					"select * from specialuservehicleinfo where lisencePlate = ? AND userId != ?",
					Specialuservehicleinfo.class, lisencePlate, userId);
		} catch (Exception e) {
			log.error("查询车牌号是否被注册过的时候出错！", e);
			throw new ServerException(ServerExpEnum.SERVER_DATABASE_EXCEPTION);
		}
		if (vlist == null || vlist.size() == 0) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * @Title: TaxiUserController.java
	 * @Package com.dingding.special.controller
	 * @Description: 出租车主重新认证
	 * @author haoxiaojun
	 * @date 2016年11月21日 下午4:41:03
	 * @version V2.5.6
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean changeCarAuthStatus(String userId, CarAuthStatus reAuth) {
		try {
			Specialuservehicleinfo specialuservehicleinfo = this.criteriaBaseDao
					.queryCriteriaListUnique(Specialuservehicleinfo.class, Restrictions.eq("userId", userId));

			if (specialuservehicleinfo != null) {
				specialuservehicleinfo.setAuthType(1);//1：缺省值(游客) 2：专车车主 3:出租车车主 （修改用户角色值）
				specialuservehicleinfo.setSuvStatus(reAuth.getCode());
				return true;
			} else {
				throw new BussinessException(BizExpEnum.NOT_FOUND_USERS_VEHICLEINFO);
			}
		} catch (Exception e) {
			log.error("存储审核记录错误！DriverUserDaoImpl ： recordDriverAuth()", e);
			throw new ServerException(ServerExpEnum.SERVER_DATABASE_EXCEPTION);
		}
	}

	/**
	 * @Description 修改用户登录表中的用户角色
	 * @author fengshuonan
	 */
	@Override
	public void changeUserRole(String userId, Integer userRole) {
		Specialuserlogin specialuserlogin = this.baseDaoX.getById(userId, Specialuserlogin.class);
		if(specialuserlogin == null){
			return ;
		}else{
			specialuserlogin.setUserRole(userRole);
		}
	}
}
